﻿using System;
using System.Net;
using SomeKit.Authentication;
using System.IO;

namespace SomeKit.Http
{
    public static partial class HttpHelper
    {
        #region Convenience methods.
        /// <summary>
        /// Sets the accept type of the request.
        /// </summary>
        /// <param name="request">The request whose accept type is set.</param>
        /// <param name="acceptType">The accept type of the request. Usually application/xml or application/json.</param>
        public static void SetAcceptType(this HttpWebRequest request, string acceptType)
        {
            if (!string.IsNullOrEmpty(acceptType))
                request.Accept = acceptType;
        }
        /// <summary>
        /// Sets the content type of the request.
        /// </summary>
        /// <param name="request">The request whose content type is set.</param>
        /// <param name="contentType">The content type of the request.  Usually application/xml or application/json.</param>
        public static void SetContentType(this HttpWebRequest request, string contentType)
        {
            if (!string.IsNullOrEmpty(contentType))
                request.ContentType = contentType;
        }
        /// <summary>
        /// Sets the basic authentication header for the request. User name and passwords are encoded as given in the specification http://en.wikipedia.org/wiki/Basic_access_authentication.
        /// </summary>
        /// <param name="request">The request whose authorization header is being set to basic authentication credentials.</param>
        /// <param name="userName">The user name of the requestor.</param>
        /// <param name="password">The password of the requestor.</param>
        public static void SetBasicAuthentication(this HttpWebRequest request, string userName, string password)
        {
            if (string.IsNullOrEmpty(userName))
                throw new ArgumentException(string.Format("User name cannot be empty."));
            if (password == null)
                password = string.Empty;
            request.Headers[HttpRequestHeader.Authorization] = BasicAuthenticationHelper.Encode(userName, password);
        }

        /// <summary>
        /// Extension method for  WebResponse type that returns the body of a response instance as a string.
        /// </summary>
        /// <param name="response">The response</param>
        /// <returns>Body of the respose as a string</returns>
        public static string WebResponseAsString(this WebResponse response)
        {
            var responseStream = response.GetResponseStream();
            var streamReader = new StreamReader(responseStream);
            var responseString = streamReader.ReadToEnd();
            responseStream.Close();
            streamReader.Close();
            response.Close();
            return responseString;
        }
        #endregion
    }
}
